﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Collections;
using System.Web.Security;

namespace iss.sg4210.se18.team6s.Utilities
{
    public static class MenuHelper
    {
        public static string Menu(this HtmlHelper helper)
        {
            var sb = new StringBuilder();

            SiteMapNodeCollection topLevelNodes = SiteMap.RootNode.ChildNodes;
            ParseSiteConfig(topLevelNodes, SiteMap.RootNode, sb, 1, helper);
            return sb.ToString();
        }

        private static string ParseSiteConfig(SiteMapNodeCollection nodes, SiteMapNode parent, StringBuilder sb, int level, HtmlHelper helper)
        {

            // Render each top level node
            foreach (SiteMapNode node in nodes)
            {
                if (node.Roles != null)
                {
                    List<string> menuRoles = GetMenuRoles(node);

                    bool hasCurrentRoles = menuRoles != null ? menuRoles.Count > 0 : false;
                    bool isCurrentLoggedIn = IsLoggedInRoleFound(node, menuRoles);

                    if (hasCurrentRoles && isCurrentLoggedIn)
                        sb.AppendFormat("<a href='{0}'>{1}</a><br/>", node.Url, helper.Encode(node.Title));
                    else if (!hasCurrentRoles)
                        sb.AppendFormat("<a href='{0}'>{1}</a><br/>", node.Url, helper.Encode(node.Title));
                }

                if (node.ChildNodes.Count > 0)
                {
                    level++;
                    ParseSiteConfig(node.ChildNodes, node, sb, level, helper);
                    level--;
                }
            }

            return sb.ToString();
        }

        private static bool IsLoggedInRoleFound(SiteMapNode node, List<string> menuRoles)
        {
            string[] loggedInUserRoles = Roles.GetRolesForUser(Common.GetLoggedInUserName());
            return menuRoles.Intersect(loggedInUserRoles).Count<string>() > 0;
        }

        private static List<string> GetMenuRoles(SiteMapNode nodeCurrent)
        {
            List<string> menuRoles = new List<string>();
            IEnumerator roleEnum = nodeCurrent.Roles.GetEnumerator();
            while (roleEnum.MoveNext())
                menuRoles.Add((string)roleEnum.Current);

            SiteMapNode parentNode = nodeCurrent.ParentNode;
            while (parentNode != null)
            {
                roleEnum = parentNode.Roles.GetEnumerator();
                while (roleEnum.MoveNext())
                {
                    string role = (string)roleEnum.Current;
                    if (!menuRoles.Contains(role))
                        menuRoles.Add(role);
                }
                parentNode = parentNode.ParentNode;
            }

            return menuRoles;
        }
    }
}